package com.witmore.skyline.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.witmore.skyline.db.entity.CameraDO;
import com.witmore.skyline.db.entity.CameraTaskDO;
import com.witmore.skyline.db.mapper.CameraMapper;
import com.witmore.skyline.db.mapper.CameraTaskMapper;
import com.witmore.skyline.web.controller.enums.CameraPicSourceTypeEnum;
import com.witmore.skyline.web.service.CameraCaptureYinShiService;
import com.witmore.skyline.web.service.CameraService;
import com.witmore.skyline.web.service.third.constants.ApiClientCommonConstant;
import com.witmore.skyline.web.service.third.yingshi.YSApiClient;
import com.witmore.skyline.web.service.third.yingshi.dto.YSApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;

import static java.lang.String.format;

/**
 * Description: CameraCaptureYinShiServiceImpl
 * Author: 豆子高
 * Date: 2025/3/17 13:42
 */
@Slf4j
@Service
public class CameraCaptureYinShiServiceImpl implements CameraCaptureYinShiService {

    @Autowired
    private CameraMapper cameraMapper;
    @Autowired
    private CameraTaskMapper cameraTaskMapper;
    @Autowired
    private CameraService cameraService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean ysCameraCapturePicHandler(CameraDO cameraDO, CameraTaskDO cameraTaskDO) {
        boolean isSuccess = true;
        YSApiResponse deviceCapture;
        try {
            deviceCapture = YSApiClient.getDeviceCapture(cameraDO.getCameraSn());
            // 存储状态
            cameraTaskDO.setErrorCode(Integer.valueOf(deviceCapture.getCode()));
            cameraTaskDO.setErrorMsg(deviceCapture.getMessage());
            cameraTaskDO.setState(Integer.valueOf(deviceCapture.getCode()));
            cameraTaskMapper.insert(cameraTaskDO);
            // 更新数据
            if ("200".equals(deviceCapture.getCode()) && deviceCapture.getData() != null) {
                // 获取picUrl
                JSONObject data = (JSONObject) deviceCapture.getData();
                String picUrl = (String) data.get("picUrl");
                String fileName = format(ApiClientCommonConstant.OSS_FILE_UPLOAD_YS_PREFIX, cameraDO.getCameraSn())
                        + System.currentTimeMillis()
                        + ".jpg";
                String ossUrl = cameraService.convertOssUrl(fileName, picUrl);
                cameraService.saveCameraPic(cameraDO, ossUrl, CameraPicSourceTypeEnum.USER_CAPTURE_IMAGE_CLOUD);
                // 更新照片
                cameraTaskMapper.updateById(CameraTaskDO.builder()
                        .id(cameraTaskDO.getId())
                        .updateTime(LocalDateTime.now())
                        .url(ossUrl)
                        .build());
            }
        } catch (Exception e) {
            isSuccess = false;
            log.error("萤石 抓取图片失败 error cameraSn-->{},msg-->{}, e",
                    cameraDO.getCameraSn(), e.getMessage(), e);
        }
        return isSuccess;
    }


    @Override
    public void executeSubmitCapturePicTaskYS(String cameraSn) {
        int page = 1;
        int pageSize = 50;
        while (true) {
            Page<CameraDO> cameraDOPage = cameraMapper.selectPage(new Page<>(page, pageSize), new LambdaQueryWrapper<CameraDO>()
                    .eq(CameraDO::getIsDeleted, 0)
                    .in(StringUtils.isNotEmpty(cameraSn), CameraDO::getCameraSn, cameraSn)
                    .eq(CameraDO::getCameraStatus, 1)
                    .eq(CameraDO::getType, 1));
            if (cameraDOPage == null || CollectionUtils.isEmpty(cameraDOPage.getRecords())) {
                return;
            }
            cameraDOPage.getRecords().forEach(cameraDO -> {
                try {
                    YSApiResponse deviceCapture = YSApiClient.getDeviceCapture(cameraDO.getCameraSn());
                    // 更新数据
                    if ("200".equals(deviceCapture.getCode()) && deviceCapture.getData() != null) {
                        // 获取picUrl
                        JSONObject data = (JSONObject) deviceCapture.getData();
                        String picUrl = (String) data.get("picUrl");
                        String fileName = format(ApiClientCommonConstant.OSS_FILE_UPLOAD_YS_PREFIX, cameraDO.getCameraSn())
                                + System.currentTimeMillis()
                                + ".jpg";
                        String ossUrl = cameraService.convertOssUrl(fileName, picUrl);
                        cameraService.saveCameraPic(cameraDO, ossUrl,CameraPicSourceTypeEnum.SCHEDULED_TASK);
                    }
                } catch (Exception e) {
                    log.warn("萤石 创建抓取图片任务失败 error cameraSn-->{},msg-->{}, e",
                            cameraDO.getCameraSn(), e.getMessage(), e);
                }
            });
            page++;
        }
    }
}
